<?php 

namespace app\admin\controller;

use app\common\Helper;
use app\common\lib\Qiniu;

use think\Db;
use think\Controller;
use think\Request;


/**
 * 图片处理
 */
class Image extends Controller
{

    /**
     * 获取七牛token
     * @return \think\response\Json
     */
	public function token() {
		$Qiniu = new Qiniu();

		return json(['uptoken'=>$Qiniu->getToken()]);
	}

	/**
     * 图片组件-获取所有图片-客户端分页
     */
    public function getList(){
        $list = Db::name('image')->where([])->field('')->order('created DESC')->select();
        $count = Db::name('image')->where([])->count();
        $res = [
            'status' => '1',
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count
        ];

        return json($res);
    }

	/**
	 * 将上传的每一张图片记录到数据表中
	 */
	public function record() {
		$controller = 'test';
        $id = Helper::getUUID();
        $data = [
            'id' => $id,
            'imgUrl' => $_POST['imgUrl'],
            'controller' => $controller,
            'created' => time()
        ];

        $insert = Db::name('image')->insert($data);
        $code = $insert ? '1' : '2';

        return json(['image_id' => $id, 'code' => $code]);
	}

	/**
	 * 图片删除-删除记录及七牛空间中的图片
	 */
	public function delete() {
		$id = $this->request->param('id');
		$url = $this->request->param('imgUrl');
		$key =  substr(strrchr($url, '/'), 1);

		$Qiniu = new Qiniu();
		$res = $Qiniu->delImg($key);  //删除图片
		if($res == NULL){
			//Db::table('image')->where('id',$id)->delete();  //删除总表记录
            Db::name('image')->where('imgUrl', $url)->delete();  //删除总表记录
            return json(['message' => '删除成功', 'code' => '1']);
        }else{
            return json(['message' => '删除失败', 'code' => '2']);
        }
	}

}